//
//  OneViewController.m
//  半糖
//
//  Created by RenShuang on 15-9-8.
//  Copyright (c) 2015年 shuang. All rights reserved.
//

#import "OneViewController.h"
#import "firstTableModel.h"
#import "firstTableViewCell.h"
#import "firstTitleModel.h"
#import "BaseHeader.h"
#import "TableDetailViewController.h"
#import "TittleDetailViewController.h"
#import "RESideMenu.h"
#import "LeftViewController.h"

#define WIDTH [[UIScreen mainScreen] bounds].size.width
#define HEIGHT [[UIScreen mainScreen] bounds].size.height

@interface OneViewController ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate,buttonPush>
{
    UIView *upView;
}
@property(nonatomic,retain)UIScrollView *titleScrollView;
@property(nonatomic,retain)UIPageControl *pageControl;
@property(nonatomic,retain)UITableView *myTableView;
@property(nonatomic,assign)NSInteger a;
@property(nonatomic,assign)NSInteger footer;
@property(nonatomic,retain)NSMutableArray *titleArr;
@property(nonatomic,retain)NSMutableArray *modelArr;
@property(nonatomic,retain)NSMutableArray *cacheModelArr;

@end

@implementation OneViewController

- (void)dealloc
{
    [_titleScrollView release];
    [_pageControl release];
    [_myTableView release];
    [super dealloc];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    [self.myTableView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBarHidden = YES;
    
    //状态栏
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
    
    [[DataBase shareDataBase] openDB];
    [[DataBase shareDataBase] createTable];
    [[DataBase shareDataBase] createCacheTable];
    
    [self barCreate];
    
    self.view.backgroundColor = [UIColor whiteColor];
  
    
    _a = 2;
    _footer = 0;
    _titleArr = [[NSMutableArray alloc] init];
    _modelArr = [[NSMutableArray alloc] init];
    _cacheModelArr = [[NSMutableArray alloc] init];
    
    [self FooterFresh];
    //先创建tableView,在建UIVIew,设成headerView
    [self tableCreate];
    [self titleData];
    
    LeftViewController *left = [[LeftViewController alloc] init];
    left.delegate = self;
    [left release];
    
    [self.myTableView addLegendHeaderWithRefreshingBlock:^{
        [self.myTableView.header endRefreshing];
    }];
    [self.myTableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(FooterFresh)];

    
}

- (void)buttonPushToViewController
{
    SCTableViewController *sc = [[SCTableViewController alloc] initWithStyle:UITableViewStylePlain];
    [self.navigationController pushViewController:sc animated:YES];
}

//创建假的navigationBar
- (void)barCreate
{
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 64)];
    titleView.backgroundColor = [UIColor redColor];
    [self.view addSubview:titleView];
    [titleView release];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH/3, 18, SCREEN_WIDTH/3, 44)];
    //titleLabel.backgroundColor = [UIColor greenColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.text = @"潮品";
    //label加粗并放大
    titleLabel.font = [UIFont boldSystemFontOfSize:22.];
    [titleView addSubview:titleLabel];
    [titleLabel release];
    
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    backButton.frame = CGRectMake(20, 30, 30, 25);
    [backButton setBackgroundImage:[UIImage imageNamed:@"chouti.png"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(presentLeftMenuViewController:) forControlEvents:UIControlEventTouchUpInside];
    [titleView addSubview:backButton];
}

//轮播图
- (void)titleCreate
{
    upView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, WIDTH, HEIGHT/4+20)];
    _myTableView.tableHeaderView = upView;
    [upView release];
    
    _titleScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT/4+20)];
    _titleScrollView.delegate = self;
    _titleScrollView.pagingEnabled = YES;
    _titleScrollView.showsHorizontalScrollIndicator = NO;
    _titleScrollView.contentOffset = CGPointMake(WIDTH, 0);
    _titleScrollView.contentSize = CGSizeMake(WIDTH*(_titleArr.count+2), 0);
    [upView addSubview:_titleScrollView];
    [_titleScrollView release];
    
    
    for (int i = 0; i < _titleArr.count; i++) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(WIDTH*(i+1), 0, WIDTH, HEIGHT/4+20)];
        firstTitleModel *model = [_titleArr objectAtIndex:i];
        [imageView sd_setImageWithURL:[NSURL URLWithString:model.photo]];
        imageView.userInteractionEnabled = YES;
        [_titleScrollView addSubview:imageView];
        [imageView release];
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.frame = CGRectMake(0, 0, WIDTH, HEIGHT/4+20);
        button.tag = 1000+i;
        [button addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
        [imageView addSubview:button];
    }
    
    //做第一个和最后一个的图片
    firstTitleModel *firstModel = [_titleArr lastObject];
    UIImageView *imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT/4+20)];
    [imageView1 sd_setImageWithURL:[NSURL URLWithString:firstModel.photo]];
    [_titleScrollView addSubview:imageView1];
    [imageView1 release];
    
    firstTitleModel *lastModel = [_titleArr firstObject];
    UIImageView *imageView2 = [[UIImageView alloc] initWithFrame:CGRectMake(WIDTH*(_titleArr.count+1), 0, WIDTH, HEIGHT/4+20)];
    [imageView2 sd_setImageWithURL:[NSURL URLWithString:lastModel.photo]];
    [_titleScrollView addSubview:imageView2];
    [imageView2 release];
    
    
    _pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, HEIGHT/4-10, WIDTH, 30)];
    _pageControl.numberOfPages = _titleArr.count;
    _pageControl.tintColor = [UIColor whiteColor];
    [upView addSubview:_pageControl];
    [_pageControl release];
    
    [NSTimer scheduledTimerWithTimeInterval:3. target:self selector:@selector(changed) userInfo:nil repeats:YES];
}

//定时器方法
- (void)changed
{
    _titleScrollView.contentOffset = CGPointMake(WIDTH*_a, 0);
    
    _a++;
    if (_a > _titleArr.count+1) {
        _a = 0;
    }
}

//轮播图点击方法
- (void)click:(UIButton *)sender
{
    TittleDetailViewController *titleDetail = [[TittleDetailViewController alloc] init];
    firstTitleModel *modell = [_titleArr objectAtIndex:sender.tag - 1000];
    titleDetail.model = modell;
    [self.navigationController pushViewController:titleDetail animated:YES];
}

//滑动方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (_titleScrollView.contentOffset.x >= WIDTH*(_titleArr.count+1)) {
        [_titleScrollView setContentOffset:CGPointMake(WIDTH, 0) animated:NO];
    }
    if (_titleScrollView.contentOffset.x <= 0) {
        [_titleScrollView setContentOffset:CGPointMake(WIDTH*(_titleArr.count), 0) animated:NO];
    }
    _pageControl.currentPage = _titleScrollView.contentOffset.x/WIDTH-1;
    _a = _titleScrollView.contentOffset.x/WIDTH;
}

//轮播图数据
- (void)titleData
{
    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    NSString *url_string = [NSString stringWithFormat:@"http://open3.bantangapp.com/recommend/index?app_installtime=1440915950.090587&app_versions=4.1.1&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&oauth_token=6de3bace25123737e17db3e839477eb1&os_versions=8.2&page=0&pagesize=20&screensize=640&track_device_info=iPhone&track_deviceid=B4391E1B-981F-4473-A960-431F69E76E8C&track_user_id=1260331&v=6"];
    //[NSSet setWithObjects:@"text/plain",@"text/json”,net,nil];  代表支持所有的接口类型
    AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    [manager GET:url_string parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [netWorkManager stopMonitoring];
        
        NSMutableDictionary *dic = responseObject;
        NSArray *arr = [[dic objectForKey:@"data"] objectForKey:@"banner"];
            
            for (NSDictionary *dic in arr) {
                firstTitleModel *model = [[firstTitleModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [_titleArr addObject:model];
                [model release];
            }
        
        NSLog(@"titleArr = %ld",(unsigned long)_titleArr.count);
        NSLog(@"数据申请成功");
        [self titleCreate];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"失败==== %@",error);
    }];
    
}

- (void)tableCreate
{
    
    _myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, WIDTH, HEIGHT) style:UITableViewStylePlain];
    _myTableView.delegate = self;
    _myTableView.dataSource = self;
    _myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_myTableView];
    
}

//tableView数据和下拉加载
- (void)FooterFresh
{
   
    NSString *url_str = [NSString stringWithFormat:@"http://open3.bantangapp.com/recommend/index?app_installtime=1440915950.090587&app_versions=4.1.1&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&oauth_token=6de3bace25123737e17db3e839477eb1&os_versions=8.2&page=%ld&pagesize=20&screensize=640&track_device_info=iPhone&track_deviceid=B4391E1B-981F-4473-A960-431F69E76E8C&track_user_id=1260331&v=6",(long)_footer];

    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    NSString *url_string = [NSString stringWithFormat:@"%@",url_str];
    AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    [manager GET:url_string parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        [netWorkManager stopMonitoring];
        NSMutableDictionary *dic = responseObject;
        NSArray *arr = [[dic objectForKey:@"data"] objectForKey:@"topic"];
            
            for (NSDictionary *dic in arr) {
                firstTableModel *model = [[firstTableModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                model.cid = [dic objectForKey:@"id"];
                [_modelArr addObject:model];
                [model release];
            }
        
        if (_footer == 0){
            [[DataBase shareDataBase] dropCacheTable];
            [[DataBase shareDataBase] createCacheTable];
            for (firstTableModel *model in _modelArr) {
                [[DataBase shareDataBase] insertCacheStudent:model];
            }
        }
        [_myTableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"失败 === %@",error);
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"没有网啊,哎" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertView show];
            [alertView release];
            
            self.modelArr = [[DataBase shareDataBase] selectCacheAll];
            [self.myTableView reloadData];
        });
        
        
    }];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        _footer++;
        [self.myTableView.footer endRefreshing];
        [_myTableView reloadData];
    });
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _modelArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return HEIGHT*7/24;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellid = @"cell";
    firstTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellid];
    if (cell == nil) {
        cell = [[firstTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.contentView.backgroundColor = [NightHandle shareHandle].viewColor;
    firstTableModel *model = [_modelArr objectAtIndex:indexPath.row];
    [cell getcell:model];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TableDetailViewController *detail = [[TableDetailViewController alloc] init];
    firstTableModel *model = [_modelArr objectAtIndex:indexPath.row];
    detail.str = model.cid;
    detail.titleStr = model.title;
    detail.picStr = model.pic;
    [self.navigationController pushViewController:detail animated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
